package com.icinfo.cloud.provider.punish.service.impl;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.page.PageResponse;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.dto.DingUserResultDto;
import com.icinfo.cloud.provider.punish.service.IXzzfInterfaceService;
import com.icinfo.cloud.xzcf.provider.member.line.dto.LineDTO;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.cloud.xzcf.provider.member.zfpeople.dto.ZfCert;
import com.icinfo.cloud.xzcf.provider.member.zfpeople.dto.ZfPeopleBaseInfoVO;
import com.icinfo.framework.common.web.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 描述：行政执法接口服务实现类
 *
 * @author xiangyuyu
 * @date 2022/4/8 11:53
 */
@Service
@Slf4j
public class XzzfInterfaceServiceImpl implements IXzzfInterfaceService {

    @Value("${member.url}")
    private String memberUrl;

    @Value("${member.api.getPeopleBaseInfo}")
    private String getUserInfoApi;
    @Value("${member.api.getLineListByLineCodes}")
    private String getLineListByLineCodes;
    @Value("${member.api.getUser}")
    private String getUserApi;
    @Value("${member.api.getUserByZwdAccountId}")
    private String getUserByZwdAccountIdApi;

    @Value("${auth.url}")
    private String authUrl;
    @Value("${auth.api.getXzzfTokenByAccountId}")
    private String getXzzfTokenByAccountIdApi;
    /**
     * 描述：获取执法人员信息
     *
     * @param baseInfoRequest TODO：入参格式最好是优化成实体类
     * @return List<ZfPeopleBaseInfoVO>
     * @author xiangyuyu
     * @date 2022-04-08 13:54
     */
    @Override
    public List<ZfPeopleBaseInfoVO> getZfPeopleList(JSONObject baseInfoRequest) {
        log.info("getZfPeopleList start... param-baseInfoRequest:{}", baseInfoRequest);
        Map<String, String> headers = HeaderUtil.headerInfo();
        String param = JSON.toJSONString(baseInfoRequest);
        String response = HttpUtil.createPost(memberUrl.concat(getUserInfoApi)).addHeaders(headers).body(param).execute().body();
        log.info("getZfPeopleList response:{}",response);
        JSONObject info = JSONObject.parseObject(response);
        List<ZfPeopleBaseInfoVO> listDtos = new ArrayList<>();
        String code = "code";
        int th = 200;
        if (th == info.getInteger(code)) {
            PageResponse<JSONObject> users = JSON.parseObject(info.getString("data"), PageResponse.class);
            for (JSONObject object : users.getData()) {
                listDtos.add(JSON.parseObject(JSON.toJSONString(object), ZfPeopleBaseInfoVO.class));
            }
        }
        log.info("getZfPeopleList end... result-listDtos:{}", listDtos);
        return listDtos;
    }

    /**
     * 描述：获取执法证编号信息
     *
     * @param userId 用户Id
     * @return String 执法证编号信息
     * @author xiangyuyu
     * @date 2022-04-08 16:58
     */
    @Override
    public String getLawEnforcementCertWithUserId(String userId) {
        log.info("getLawEnforcementCertWithUserId start... param-userId:{}", userId);
        if (ObjectUtils.isEmpty(userId)) {
            throw new BusinessException("获取执法证编号信息时出现异常-未指定用户id");
        }
        String lawEnforcementCert = null;
        JSONObject requestInfo = new JSONObject();
        List<String> userIdList = new ArrayList<>();
        userIdList.add(userId);
        requestInfo.put("userIds", userIdList);
        List<ZfPeopleBaseInfoVO> userInfoList = getZfPeopleList(requestInfo);
        //有效证书列表
        List<String> effectiveCertNumberList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(userInfoList) && userInfoList.size() > 0) {
            ZfPeopleBaseInfoVO zfPeopleBaseInfoVO = userInfoList.get(Constant.INTEGER_0);
            List<ZfCert> zfCertList = zfPeopleBaseInfoVO.getZfCertList();
            if (!ObjectUtils.isEmpty(zfCertList) && zfCertList.size() > 0) {
                for (ZfCert c : zfCertList) {
                    String status = c.getStatus();
                    if (Constant.STRING_0.equals(status)) {
                        effectiveCertNumberList.add(c.getZfCertNo());
                    }
                }
            } else {
                log.error("未匹配到执法证编号信息 userId:{}", userId);
            }
        } else {
            log.error("未匹配到执法人员信息 userId:{}", userId);
        }
        if (effectiveCertNumberList.size() > 0) {
            lawEnforcementCert = effectiveCertNumberList.toString().replace("[", "").replace("]", "");
        } else {
            log.error("未匹配到有效的执法证编号信息 userId:{}", userId);
        }
        log.info("getLawEnforcementCertWithUserId end... result-lawEnforcementCert:{}", lawEnforcementCert);
        return lawEnforcementCert;
    }
    /**
     * 描述：根据条线code获取条线信息
     *
     * @return {@link LineDTO }
     * @author shishengyao
     * @date 2022/06/29
     */
    @Override
    public LineDTO getLineInfoByLineCode(String lineCode){
        log.info("getLineListByLineCodes start... param-baseInfoRequest:{}", getLineListByLineCodes);
        Map<String, String> headers = HeaderUtil.headerInfo();
        List<String> linecodes=new ArrayList<>();
        linecodes.add(lineCode);
        JSONObject requestInfo = new JSONObject();
        requestInfo.put("codes", linecodes);
        String param = JSON.toJSONString(linecodes);
        String response = HttpUtil.createPost(memberUrl.concat(getLineListByLineCodes)).addHeaders(headers).body(param).execute().body();
        log.info("getLineListByLineCodes response:{}",response);
        JSONObject info = JSONObject.parseObject(response);
        List<LineDTO > lineDTOList = new ArrayList<>();
        String code = "code";
        int th = 200;
        if (th == info.getInteger(code)) {
            List<JSONObject> lineList = JSON.parseObject(info.getString("data"), List.class);
            for (JSONObject object : lineList) {
                lineDTOList.add(JSON.parseObject(JSON.toJSONString(object), LineDTO.class));
            }
        }
        log.info("getLineListByLineCodes end... result-lineDTOList:{}", lineDTOList);
        if (lineDTOList.size()>0){
            return  lineDTOList.get(0);
        } else {
            log.error("未匹配到有效的条线信息 lineCode:{}", lineCode);
        }
        return null;
    }

    /**
     * 描述： 根据用户id获取办案人员信息
     *
     * @author: zhengqiang
     * @date: 2022/8/27
     * @param: userId
     * @return {@link UserDTO}
     **/
    @Override
    public UserDTO getUserByUserId(String userId) {
        Map<String, Object> urlParam = Collections.singletonMap("userId", userId);
        Map<String, String> headers = HeaderUtil.headerInfo();
        log.info("getUser start... param:{}", urlParam);
        try {
            String response = HttpUtil.createGet(memberUrl.concat(getUserApi)).addHeaders(headers).form(urlParam).execute().body();
            log.info("getUser response:{}", response);
            if (ObjectUtils.isEmpty(response)) {
                return null;
            }
            Result result = JSONObject.parseObject(response, Result.class);
            if (HttpStatus.HTTP_OK == result.getCode() && !ObjectUtils.isEmpty(result.getData())) {
                UserDTO userDTO = JSONObject.parseObject(result.getData().toString(), UserDTO.class);
                return userDTO;
            }
        } catch (HttpException e) {
            e.printStackTrace();
            log.error("getUser异常:{}", e);
        }
        return null;
    }

    /**
     * 描述： 根据浙政钉id获取用户信息
     *
     * @author: zhengqiang
     * @date: 2022/8/19
     * @param: ZwdingAccountId
     * @return {@link DingUserResultDto}
     **/
    @Override
    public JSONObject getUserByZwdAccountId(String ZwdingAccountId) {
        Map<String, Object> urlParam = Collections.singletonMap("zwdingAccountId", ZwdingAccountId);
        log.info("getUserByZwdAccountId start... param:{}", urlParam);
        String response = HttpUtil.createGet(memberUrl.concat(getUserByZwdAccountIdApi)).form(urlParam).execute().body();
        log.info("getUserByZwdAccountId response:{}", response);
        if (ObjectUtils.isEmpty(response)) {
            return null;
        }
        return JSONObject.parseObject(response);
    }


    /**
     * 描述： 根据accountId获取用户token
     *
     * @author: zhengqiang
     * @date: 2022/12/9
     * @param: accountId
     * @return {@link String}
     **/
    @Override
    public String getXzzfTokenByAccountId(String accountId) {
        //获取用户token信息
        Map<String, Object> urlParamOfToken = Collections.singletonMap("accountId", accountId);
        log.info("getXzzfTokenByAccountId start... param:{}", urlParamOfToken);
        String tokenResponse = HttpUtil.createGet(authUrl.concat(getXzzfTokenByAccountIdApi)).form(urlParamOfToken).execute().body();
        log.info("getXzzfTokenByAccountId response:{}", tokenResponse);
        if (ObjectUtils.isEmpty(tokenResponse)) {
            return null;
        }
        Result result = JSONObject.parseObject(tokenResponse, Result.class);
        if (HttpStatus.HTTP_OK != result.getCode()) {
            return null;
        }
        JSONObject object = JSONObject.parseObject(result.getData().toString());
        String token = object.getString("token");
        return token;
    }
}
